package com.atguigu.tingshu.order.task;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.order.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@Slf4j
public class RedisDelayHandle {

    @Autowired
    private RedissonClient redissonClient ;

    @Autowired
    private OrderInfoService orderInfoService ;

    @Scheduled(cron = "0/1 * * * * ?")
    public void orderCancelDelayQueueHandle() {

        RLock rLock = redissonClient.getLock(RedisConstant.DELAY_QUEUE_ORDER_LOCK);
        boolean tryLock = rLock.tryLock();          //  使用分布式锁解决集群环境下任务的重复执行问题
        if(tryLock) {

            try {

                // 从Redis中获取延迟任务
                RBlockingDeque<String> blockingDeque = redissonClient.getBlockingDeque(RedisConstant.DELAY_QUEUE_ORDER_CANCEL);
                String orderNo = blockingDeque.poll();
                if(!StringUtils.isEmpty(orderNo)) {
                    orderInfoService.canalOrder(orderNo) ;
                }

            }catch (Exception e) {
                e.printStackTrace();
            }finally {
                rLock.unlock();
            }

        }


    }

}
